import { Button, Stack, Typography } from '@mui/material'
import { styled } from '@mui/material/styles'
import Image, { ImageType } from './image'
import { TCatalogData } from '../../store/types'
import { useAppDispatch, useAppSelector } from '../../hooks'
import { selectCartProducts } from '../../store/reducers/selectors'
import AmountSelector from '../cart/amountSelector'
import { cartSlice } from '../../store/reducers/slices/cartSlice'
import DeleteFromCartButton from '../cart/deleteFromCartButton'

export type TCardProps = TCatalogData & {
	discountPrice?: number
	type: ImageType
}

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	alignItems: 'center',
	flexDirection: 'column',
	width: '236px',
	height: '359px',
}))

const StyledDiscountPrice = styled(Typography)(() => ({
	textDecoration: 'line-through',
	fontSize: '12px',
	fontFamily: 'Nunito',
	minHeight: '30px',
}))

const StyledPrice = styled(Typography, {
	shouldForwardProp: (props) => props !== 'discount',
})<Pick<TCardProps, 'discount'>>(({ discount }) => ({
	fontSize: '20px',
	fontWeight: discount ? 'Bold' : 'Regular',
	color: discount ? 'red' : 'black',
	fontFamily: 'Nunito',
}))

const StyledQuantity = styled(Typography)(() => ({
	fontSize: '12px',
	fontWeight: 'Regular',
	color: '#7B8E98',
	fontFamily: 'Nunito',
}))

const StyledName = styled(Typography)(() => ({
	height: '44px',
	fontSize: '16px',
	fontWeight: 'Semibold',
	color: '#1A1A1A',
	fontFamily: 'Nunito',
	overflow: 'hidden',
}))

const StyledButton = styled(Button)(() => ({
	width: '121px',
	height: '40px',
	borderRadius: '55px',
	background: '#FFE44D',
	border: '0px',
	'&': {
		color: '#1A1A1A',
		textTransform: 'none',
	},
}))

const Card = ({
	_id,
	pictures,
	stock,
	discount,
	discountPrice,
	price,
	wight,
	name,
	type,
}: TCardProps) => {
	const dispatch = useAppDispatch()
	const cartProducts = useAppSelector(selectCartProducts)
	const addedToCart = cartProducts?.find((product) => product._id === _id)
	function handleClick() {
		dispatch(
			cartSlice.actions.addProduct({
				_id: _id,
				name: name,
				pictures: pictures,
				stock: stock,
				price: price,
				purchaseAmount: 1,
				discount: discount,
			})
		)
	}

	return (
		<StyledContainer>
			<Image _id={_id} type={type} discount={discount} pictures={pictures} />
			<StyledDiscountPrice>{discount !== 0 ? price : ''}</StyledDiscountPrice>
			<StyledPrice discount={discount}>{discountPrice}</StyledPrice>
			<StyledQuantity>{wight}</StyledQuantity>
			<StyledName>{name}</StyledName>
			{addedToCart ? (
				<Stack direction={'row'} spacing={2}>
					<AmountSelector _id={_id} />
					<DeleteFromCartButton _id={_id} />
				</Stack>
			) : (
				<StyledButton variant='outlined' onClick={handleClick}>
					<Typography>{stock > 1 ? 'В корзину' : 'Закончился'}</Typography>
				</StyledButton>
			)}
		</StyledContainer>
	)
}

export default Card
